package com.lzb.common.interceptor;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import com.lzb.common.datasource.MultipleDataSource;
import com.lzb.common.datasource.ServiceDataSourceAnnotation;

@Component(ReadWriteSplittingInterceptor.BEAN_PACKAGE_NAME)
@Aspect
public class ReadWriteSplittingInterceptor implements Ordered {

	public static final String BEAN_PACKAGE_NAME = "com.lzb.common.interceptor.ReadWriteSplittingInterceptor";
	
	public ReadWriteSplittingInterceptor() {}
	
	/*
	 * 注意：数据源的切换只能在Service进行，因为Spring进行AOP事务的代理对象生成过程中，会设置数据源，所以就算我们这里设置成DAO切换数据源，
	 * 也不会生效。
	 * 只有在读写分离的场景，适合在DAO层进行数据源切换，而且这种做法，是否能实现负载均衡？还是用代理会更好？
	 * 如果是更新多个数据库的操作，事务管理还是放在Service层，需要用到分布式事务
	 * 
	 * */
	@Before("execution(* com.lzb..service..*.*(..))")
	public void before(JoinPoint jp) {
        try {
            Method preparedMethod = ((MethodSignature)jp.getSignature()).getMethod();
            if (preparedMethod != null && preparedMethod.isAnnotationPresent(ServiceDataSourceAnnotation.class)) {
                ServiceDataSourceAnnotation data = preparedMethod.getAnnotation(ServiceDataSourceAnnotation.class);
                MultipleDataSource.setDataSourceKey(data.getServiceDataSource());
            } else {
            	MultipleDataSource.setDataSourceKey(MultipleDataSource.DATA_SOURCE_MASTER);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
	}

	@Override
	public int getOrder() {
		return 2;
	}
}